<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :destroyOnClose="true"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="所属风场" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="this.flag">
          <j-select-depart v-decorator="['orgName']" :trigger-change="true" v-on:orgname="getorgname"  @change="change()"/>
        </a-form-item>
        <a-form-item label="风机" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="this.flag">
          <j-search-select-tag type="list" v-decorator="['productId',validatorRules.productId]" :trigger-change="true" v-on:show="getfanid" dictCode="" placeholder="请选择风机id" setFieldsValue="selectValue" :dictOptions="dictOption"/>
        </a-form-item>
         <a-form-item label="父节点" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-tree-select
            ref="treeSelect"
            placeholder="请选择父节点"
            v-decorator="['parentId']"
            dict="dt_equipment_tree,name,id"
            pidField="parent_id"
            pidValue="0"
            hasChildField="has_child">
          </j-tree-select>
        </a-form-item>
        
        <a-form-item label="节点名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['name',validatorRules.name]" placeholder="请输入节点名称"></a-input>
        </a-form-item>
        <a-form-item label="图片地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-image-upload isMultiple v-decorator="['imageUrl']"></j-image-upload>
        </a-form-item>
       
        
        
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>

  import { httpAction,getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
  import store from '@/store'
  import {setCookie} from '@/utils/cookie'
  
  export default {
    name: "DtEquipmentTreeModal",
    components: { 
      JImageUpload,
      JSelectDepart,
      JDictSelectTag,
      JTreeSelect,
      JSearchSelectTag
    },
    props:['data'],
    data () {
      return {
        fanid:'',
        idstr:'',
        flag:true,
        selectValue:'',
        dictOption:[],
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules: {
        },
        url: {
          add: "/dtequipmenttree/dtEquipmentTree/add",
          edit: "/dtequipmenttree/dtEquipmentTree/edit",
        },
        expandedRowKeys:[],
        pidField:"parentId",
        validatorRules: {
          productId: {
            rules: [
              { required: true, message: '请输入风机!'},
            ]
          },
          name: {
            rules: [
              { required: true, message: '请输入节点名称!'},
            ]
          },
        },
     
      }
    },
    created () {
    },
    methods: {
       change(){
         
      if(this.idstr == ''){
        this.idstr = store.getters.userInfo.departIds
      }
       var param = {
        orgName:this.idstr,
        pageSize:99999
      }
      
         getAction('/product_manage/dtPCode/queryFanDetail',param).then(res=>{
           this.dictOption = [];
           console.log('11',this.dictOption)
           if(res.result.records.length>0){
            for(var i=0; i<res.result.records.length;i++){
              this.dictOption.push({
                text:res.result.records[i].fanName,
                value:res.result.records[i].id,
              })
            }
           }else{
              this.dictOption.push({
                text:"",
                value:"",
              })
           }
             
            console.log('22',this.dictOption)
          })

          this.$refs.treeSelect.loadRoot(this.idstr)  //查询父节点
    },
       getorgname(idstr){
      this.idstr = idstr
    },
    getfanid(selectedValue){
      console.log('this.fanid',selectedValue)
      this.fanid = selectedValue
    },
      add (obj) {
        this.edit(obj);
      },
      edit (record) {
        if(record != undefined){
          console.log('编辑',record)
          this.flag = false
        }  else{
          this.flag = true
        }
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        console.log("this.model--->",this.model);
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'name','imageUrl','parentId','productId','orgName'))
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          console.log("values=",values);
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let old_pid = this.model[this.pidField]
            let formData = Object.assign(this.model, values);
            let new_pid = this.model[this.pidField]
            console.log("formData.id",formData.id);
            if(formData.id==undefined){
                console.log("添加下级或新增");
                formData.orgName = this.idstr
                formData.productId = this.fanid
            }else{
                console.log("编辑");
            }
            
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                this.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
         
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'name','imageUrl','parentId','productId','orgName'))
      },
      submitSuccess(formData,flag){
        if(!formData.id){
          let treeData = this.$refs.treeSelect.getCurrTreeData()
          console.log('treedata',treeData)
          this.expandedRowKeys=[]
          this.getExpandKeysByPid(formData[this.pidField],treeData,treeData)
          this.$emit('ok',formData,this.expandedRowKeys.reverse());
        }else{
          this.$emit('ok',formData,flag);
        }
      },
      getExpandKeysByPid(pid,arr,all){
        if(pid && arr && arr.length>0){
          for(let i=0;i<arr.length;i++){
            if(arr[i].key==pid){
              this.expandedRowKeys.push(arr[i].key)
              this.getExpandKeysByPid(arr[i]['parentId'],all,all)
            }else{
              this.getExpandKeysByPid(pid,arr[i].children,all)
            }
          }
        }
      }
      
      
    },
    mounted(){
     
    }
  }
</script>